package cn.com.easy.permission.web.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.com.easy.permission.dao.ResourceDao;
import cn.com.easy.permission.dao.RoleDao;
import cn.com.easy.permission.model.ResourceModel;
import cn.com.easy.permission.model.RoleModel;
import cn.com.easy.permission.service.system.urlreserve.anotion.UrlReserveAnotion;
import cn.com.easy.permission.web.dto.MessageDTO;
import cn.com.easy.utils.ResponseOutputUtils;

import com.google.common.collect.Lists;

/**
 * 功能菜单管理
 * 
 * @author nibili 2015年12月9日
 * 
 */
@Controller
@RequestMapping("/manage/system/authorization")
public class SystemAuthorizationController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(SystemAuthorizationController.class);

	/** 权限资源表dao */
	@Autowired
	private ResourceDao resourceDao;
	/** 角色dao */
	@Autowired
	private RoleDao roleDao;

	/**
	 * 权限管理首页
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @author nibili 2015年12月9日
	 */
	@UrlReserveAnotion("权限管理首页")
	@RequestMapping("")
	public String index(HttpServletRequest request, HttpServletResponse response) {
		return "/system/system_authorization/system_authorization";
	}

	/**
	 * 获取权限树
	 * 
	 * @param request
	 * @param response
	 * @author nibili 2015年12月8日
	 */
	@UrlReserveAnotion("获取权限树")
	@RequestMapping("/get/all")
	public void getAllAuthorization(HttpServletRequest request, HttpServletResponse response) {
		try {
			List<ResourceModel> list = resourceDao.findAll(new Sort(new Order(Direction.ASC, "showIndex")));
			if (CollectionUtils.isEmpty(list) == true) {
				// 初始根节点
				ResourceModel resourceModelTemp = new ResourceModel();
				resourceModelTemp.setId(-1l);
				resourceModelTemp.setName("根");
				resourceModelTemp.setCreateBy(this.getCurrentUser(request).getLoginname());
				resourceModelTemp = resourceDao.save(resourceModelTemp);
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, Lists.newArrayList(resourceModelTemp)));
			} else {
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, list));
			}

		} catch (Exception ex) {
			logger.error("获取所有成员异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "获取权限树异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/**
	 * 添加权限
	 * 
	 * @param request
	 * @param response
	 * @author nibili 2015年12月8日
	 */
	@UrlReserveAnotion("添加权限")
	@RequestMapping("/save")
	public void addAuthorization(HttpServletRequest request, HttpServletResponse response, ResourceModel resourceModel) {
		try {
			if (resourceModel.getId() == null) {
				if (resourceModel.getParentId() == null) {
					ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "新增权限，父节点id，不能为空！"));
					return;
				}
				// 新增
				resourceModel.setCreateBy(this.getCurrentUser(request).getLoginname());
				resourceDao.save(resourceModel);
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, resourceModel));
			} else {
				// 更新
				ResourceModel resourceModelTemp = resourceDao.findOne(resourceModel.getId());
				if (resourceModelTemp == null) {
					ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "提交权限失败，未找到用户！"));
					return;
				} else {
					resourceModelTemp.setLastModifyBy(this.getCurrentUser(request).getLoginname());
					resourceModelTemp.setName(resourceModel.getName());
					resourceModelTemp.setUrl(resourceModel.getUrl());
					resourceModelTemp.setMenuIcon(resourceModel.getMenuIcon());
					resourceModelTemp.setShowIndex(resourceModel.getShowIndex());
					resourceDao.save(resourceModelTemp);
					ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, ""));
				}
			}

		} catch (Exception ex) {
			logger.error("提交权限信息异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "提交权限信息异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/**
	 * 删除权限
	 * 
	 * @param request
	 * @param response
	 * @param id
	 * @author nibili 2015年12月9日
	 */
	@UrlReserveAnotion("删除权限")
	@RequestMapping(value = "/delete")
	public void deleteAuthorization(HttpServletRequest request, HttpServletResponse response, Long id) {
		try {
			// 子节点数量
			Integer count = resourceDao.countByParentId(id);
			if (count != null && count > 0) {
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "权限节点下存在其他权限，不能直接删除！"));
				return;
			}
			// 授权到的角色，有关联到角色不能删除
			List<RoleModel> roles = roleDao.findByResourceId(id);
			if (CollectionUtils.isNotEmpty(roles) == true) {
				List<String> roleNames = Lists.newArrayList();
				for (RoleModel role : roles) {
					roleNames.add(role.getName());
				}
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "当前菜单关联到其他角色，不能直接删除！<br/>角色：" + StringUtils.join(roleNames, "，")));
				return;
			}

			resourceDao.delete(id);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, ""));

		} catch (Exception ex) {
			logger.error("删除成员异常，id:" + id, ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "删除成员异常.ex:" + ex.getLocalizedMessage()));
		}
	}
}
